package com.github.McPlugin.vexview;

import com.connorlinfoot.titleapi.TitleAPI;
import com.github.McPlugin.main;
import com.github.McPlugin.sql.*;
import com.github.McPlugin.util.SavaItemStack;
import com.github.McPlugin.util.Task.PlayerTasks;
import com.github.McPlugin.util.Task.Task;
import com.github.McPlugin.util.Task.TasksTool;
import com.github.McPlugin.util.TransmissionEffect;
import com.github.McPlugin.util.VaultUtil;
import lk.vexview.api.VexViewAPI;
import lk.vexview.event.ButtonClickEvent;
import lk.vexview.gui.components.VexButton;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scheduler.BukkitRunnable;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class GuiEvent implements Listener {


    @EventHandler
    public static void taskEvent(ButtonClickEvent event){
        int id = (int) event.getButtonID();
        Player player = event.getPlayer();
        VexButton buttonById = event.getGui().getButtonById(id);
        if(buttonById.getName().equalsIgnoreCase("领取任务")){
            Iterator<Task> it_daily = TasksTool.list_DailyTask.iterator();
            while(it_daily.hasNext()){
                Task task = it_daily.next();
                if(task.getID() == id){
                    Task nt = new Task();
                    nt.setID(task.getID());
                    nt.setTaskName(task.getTaskName());
                    nt.setTaskType(task.getTaskType());
                    nt.setTasks(task.getTasks());
                    nt.setTaskDescription(nt.getTaskDescription());
                    TasksTool.addPlayerTasks(player,nt);
                    main.plugin.getLogger().info("领取任务完成");
                    player.closeInventory();
                    VexViewAPI.openGui(player,MyGui.tasksGui(player));
                    player.sendMessage(task.getTaskName() + "任务已领取！");
                }
            }
        }else if(buttonById.getName().equalsIgnoreCase("任务中")){
            Iterator<PlayerTasks> it_cancel = TasksTool.list_tasks.iterator();
            while(it_cancel.hasNext()){
                PlayerTasks playerTasks = it_cancel.next();
                if(playerTasks.getPlayer().getUniqueId() == player.getUniqueId()){
                    List<Task> list_task = playerTasks.getList_task();
                    Iterator<Task> it_task = list_task.iterator();
                    while (it_task.hasNext()){
                        Task task = it_task.next();
                        if(task.getID() == id){
                            it_task.remove();
                            main.plugin.getLogger().info("取消任务完成");
                            player.closeInventory();
                            VexViewAPI.openGui(player,MyGui.tasksGui(player));
                        }

                    }
                }


            }

        }
    }

    @EventHandler
    public static void signInEvent(ButtonClickEvent event) {
//        VexButton buttonById = event.getGui().getButtonById(50);
        int id = (int) event.getButtonID();
        Player player = event.getPlayer();
        if(id == 110){
            String xStr = event.getGui().getTextField(105).getTypedText();
            String yStr = event.getGui().getTextField(106).getTypedText();
            String zStr = event.getGui().getTextField(107).getTypedText();
            if(xStr.length()!=0 && yStr.length()!=0 && zStr.length()!=0) {
                double x = Double.parseDouble(xStr);
                double y = Double.parseDouble(yStr);
                double z = Double.parseDouble(zStr);
                Location location = new Location(player.getWorld(), x, y, z);

                TransmissionEffect.spreadSphereEffect(player, location);
            }

        }else {

            new BukkitRunnable() {
                @Override
                public void run() {
                    if (id >= 1 && id <= 31) {
                        LocalDate localDate = LocalDate.now();
                        int day = localDate.getDayOfMonth();
                        player.sendMessage("你点击的是id " + id);
                        //获取玩家签到信息
                        ArrayList<String> strings = SQLiteManager.get().queryPlayerAttendance(player);
                        int totalTime = 0;
                        String monthRecord = "0000000000000000000000000000000";
                        if (strings.size() != 0) {
                            totalTime = Integer.parseInt(strings.get(0));
                            monthRecord = strings.get(1);
                            main.plugin.getLogger().info("全部：" + totalTime + " 记录" + monthRecord);
                        } else {
                            main.plugin.getLogger().info("出现错误，请检查");
                        }
                        //判断进行签到
                        if (id == day) {
                            //当天有没有签到，有的话不签到，没得话签到
                            if (monthRecord.charAt(id - 1) == '0') {
                                //没签到，得奖励，存数据
                                ItemStack itemStack = new ItemStack(Material.APPLE, 1);
                                PlayerInventory inventory = player.getInventory();
                                inventory.addItem(itemStack);
                                player.updateInventory();
                                //存数据
                                totalTime++;
                                monthRecord = monthRecord.substring(0, id - 1) + "1" + monthRecord.substring(id);
                                SQLiteManager.get().updatePlayerAttendance(player, totalTime, monthRecord);
                            }
                        } else if (id < day) {
                            if (monthRecord.charAt(id - 1) == '0') {
                                //补签到，得奖励，存数据
                                ItemStack itemStack = new ItemStack(Material.APPLE, 1);
                                PlayerInventory inventory = player.getInventory();
                                inventory.addItem(itemStack);
                                player.updateInventory();
                                //这里会补签，消耗经济（暂时没写）
                                event.getButton().setUrl("[local]Login\\N" + id + ".png");
                                event.getButton().setUrl2("[local]Login\\N" + id + ".png");
                                main.plugin.getLogger().info("补签完成！！！！");
                                totalTime++;
                                monthRecord = monthRecord.substring(0, id - 1) + "1" + monthRecord.substring(id);
                                SQLiteManager.get().updatePlayerAttendance(player, totalTime, monthRecord);
                            } else {
                                //显示提示信息
                            }
                        } else {
                            //显示提示信息
//                            buttonById.setName("§5时间未到,无法签到");
//                        TitleAPI.sendTitle(player,1,2,1,"时间未到，无法签到","重新打开刷新");
                        }
                        new BukkitRunnable() {
                            @Override
                            public void run() {
                                VexViewAPI.openGui(player, MyGui.loginGui(player));
                            }
                        }.runTaskAsynchronously(main.plugin);
                    }


                }
            }.runTaskAsynchronously(main.plugin);
        }
    }


    @EventHandler
    public static void playerBuyInStore(InventoryClickEvent event){
        Player player = (Player) event.getWhoClicked();
        Inventory inventory = event.getInventory();
        if(inventory.getTitle().equalsIgnoreCase("商店(点击购买)")){
            event.setCancelled(true);
            ItemStack item = inventory.getItem(event.getRawSlot());
            if(item != null){
                ItemMeta itemMeta = item.getItemMeta();
                List<String> lore = itemMeta.getLore();
                if(lore.size()>=2) {
                    int id = Integer.parseInt(lore.get(0).split(":")[1]);
                    int price = Integer.parseInt(lore.get(1).split(":")[1]);
                    //判断能否购买
                    if(VaultUtil.seeMoney(player.getUniqueId())>=price){
                        if(item.getAmount()>0){
                            //玩家减去金钱
                            VaultUtil.pay(player.getUniqueId(),price);
                            //商店更新
                            item.setAmount(item.getAmount()-1);
                            //玩家背包增加
                            PlayerInventory playerInventory = player.getInventory();
                            playerInventory.addItem(new ItemStack(item.getType()));
                            //更新
                            player.updateInventory();

                            player.sendMessage("恭喜你购得"+item.getType().toString()+"一个");
                            //更新数据库
                            //数据库货物减一
                            main.plugin.getLogger().info("物品数量"+item.getAmount());
                            new BukkitRunnable() {
                                @Override
                                public void run() {
                                    SQLiteManager.get().updateGoods(id,item.getAmount());
                                }
                            }.runTaskAsynchronously(main.plugin);
                            //数据库购买记录加一条
                            new BukkitRunnable() {
                                @Override
                                public void run() {
                                    String name = SavaItemStack.getString(new ItemStack(item.getType()));
                                    SQLiteManager.get().insertSell(id,player.getUniqueId().toString(),name,1,price);
                                }
                            }.runTaskAsynchronously(main.plugin);
                        }else{
                            player.sendMessage("商店货物不足");
                        }
                    }else {
                        player.sendMessage("您的金钱不够");
                    }
                }

            }
        }else{
            return;
        }

        //下一个



    }
}
